# coding: utf8

"""
This file is part of PeerTool, a web application for collaborative
decision-making (Copyrighted, 2009-2010, Ellis & Grant, Inc.)
Developed by Michael F. Ellis <michael.f.ellis@gmail.com>.  
License: AGPL v3
PeerTool comes with ABSOLUTELY NO WARRANTY.
"""                
@auth.requires_login()     
def index():
    """ Present a form with sliders to evaluate all solutions
        over all criteria as well as weights for all criteria.
        Process the results and store them.
    """
    if request.args and request.args[0] != None:
        session.problemid = int(request.args[0])
    debug("auth.user.id = %s"%str(auth.user.id))
    isEmptyHtml = ptproblem.isEmptyHtml
    addcmt = ptproblem.addComment
    problem = loadProblem(session.problemid)
    if problem==None:
        redirect(URL(r=request, c='choose', f='index'))
    form = problemresponseform(problem,auth.user.id)  
    #import pdb; pdb.set_trace()      
    if form.accepts(request.vars, session, keepvalues=True):
        #import pdb; pdb.set_trace()    
        ## Set up dictionaries to pass as args needed
        ## by Problem.acceptResponses()
        sdict = {}
        cdict = {}
        sdeldict = {}
        cdeldict = {}
        for sid in problem.solutions.keys():
            sdict[sid] = []            
             
        response.flash = 'form accepted.'
        
        debug("%s"%str(form.vars))
        
        ## Decode field names to extract solution and criteria ids.
        ## Solution responses have names like 'solution0_criterion1' and
        ## criteria responses have names like 'criterion1'.
        for k,v in form.vars.iteritems():
            if k.startswith("solution"):
                s,c = k.split('_')
                sdict[s].append([c,v])
                
            elif k.startswith('criterion'):
                cdict[k] = v

            elif k.startswith('delsolution'):
                sid = k[3:]                     # e.g. 'solution5'
                sdeldict[sid] = v 
            
            elif k.startswith('delcriterion'):
                cid = k[3:]                     # e.g. 'criterion1'
                cdeldict[cid] = v 
            
            elif k.startswith('addcomment'):
                id = k[len('addcomment'):]      # i.e.  'solution...', 
                                                # 'criterion...', or 'problem'
                if id.startswith('solution'):
                    target = problem.solutions[id]
                elif id.startswith('criterion'):
                    target = problem.criteria[id]
                elif id == 'problem':
                    target = problem

                ## Add new comment to target
                if not isinstance(v,str):
                    debug("Bogus! k=%s v=%s"%(k,repr(v)))
                elif not isEmptyHtml(v):
                    au = auth.user
                    who = au.first_name + " " + au.last_name
                    addcmt(target,who,v)
                


        ## Store user's submissions in the problem object.        
        try:
            problem.acceptResponses(auth.user.id,
                cdict,sdict,cdeldict,sdeldict)
        except AssertionError:                  # from problem.addResponse()
            session.flash = T("Another user has "\
            "added new items. Please "\
            "respond and resubmit.")
            redirect(URL(r=request, c='respond',f = 'index'))

        ## Pickle the updated object
        session.problem = mergeresponses(auth.user.id, problem, 
                                        problemid=session.problemid)
                        
        redirect(URL(r=request, c='results', f='index'))
    elif form.errors:
        response.flash = 'form has errors'
    return dict(form=form, problem=problem, problemid=session.problemid)


def problemresponseform(problem,user):
    debug("Entering ...")
    fields = []
    fields.append(Field('addcommentproblem', 'text'))
    #import pdb; pdb.set_trace()
    sorted = problem.sortSolutionsReverseChrono()
    csorted = problem.sortCriteriaReverseChrono()
    for sid,s in sorted:
        try:
            ischecked = s.deletionvotes[user]
        except KeyError:
            ischecked = False  
            
        fields.append(Field("del%s"%sid, 'boolean',
                        default=ischecked,
                        comment=XML(s.text),
                        ))

        for cid,c in csorted:
            clabel = ptproblem.mkLabel(c.text, 32)
            try:
                lastresponse = s.responses[user][cid]
            except KeyError:
                lastresponse = 0.0    

            fields.append(Field("%s_%s"%(sid,cid), 'double', label=clabel, 
                                default=lastresponse,  ## no rescaling
                                ))
        fields.append(Field('addcomment%s'%sid, 'text'))

    for cid,c in csorted:
        try:
            ischecked = c.deletionvotes[user]
        except KeyError:
            ischecked = False
        fields.append(Field("del%s"%cid, 'boolean',
                        default=ischecked,
                        comment=XML(c.text,sanitize=True),
                        ))

        try:
            lastresponse = c.responses[user]
        except KeyError:
            lastresponse = 0.0 

        fields.append(Field(cid, 'double', label="Weight", 
                                default=lastresponse,  ## no rescaling
                                ))
                                       
        fields.append(Field('addcomment%s'%cid, 'text'))
    myform = SQLFORM.factory(*fields)
    debug("Leaving ...")
    return myform

    
